package com.word.template.util;


import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;

/*****
 * word转换pdf
 * 需要引入jar包：aspose-words-15.8.0-jdk16.jar
 */
@Slf4j
public class Word2PDF {

    public static boolean getLicense() {
        try {
            ClassPathResource resource = new ClassPathResource("pdfconfig" + File.separator + "license");
            License aposeLic = new License();
            aposeLic.setLicense(resource.getInputStream());
            return true;
        } catch (Exception e) {
            log.error("获取license文件失败", e);
            throw new RuntimeException("转换pdf异常(NOT FOUND LICENSE)");
        }
    }

    public static byte[] doc2pdf(ByteArrayOutputStream outputStream) {
       // String inPath = wordName;
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            throw new RuntimeException("NOT FOUND LICENSE FILE");
        }
        try {
            long old = System.currentTimeMillis();
            InputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray());
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            Document doc = new Document(byteArrayInputStream); // Address是将要被转化的word文档
            doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            byteArrayInputStream.close();
            outputStream.close();
            // EPUB, XPS, SWF 相互转换
            long now = System.currentTimeMillis();
            byte[] bytes = os.toByteArray();
            System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒"); // 转化用时
            return bytes;
        } catch (Exception e) {
            log.error(e.toString());
        }
        return null;
    }
}
